package com.cxhc.system.service.app.impl;

import cn.hutool.core.date.DateUtil;
import com.cxhc.common.utils.DateUtils;
import com.cxhc.common.utils.SecurityUtils;
import com.cxhc.system.domain.app.Examination;
import com.cxhc.system.domain.app.ExaminationQuestion;
import com.cxhc.system.domain.app.ExaminationUserQuestion;
import com.cxhc.system.domain.app.QuestionBank;
import com.cxhc.system.mapper.app.ExaminationAppMapper;
import com.cxhc.system.mapper.app.ExaminationQuestionMapper;
import com.cxhc.system.mapper.app.ExaminationUserQuestionMapper;
import com.cxhc.system.mapper.app.QuestionBankMapper;
import com.cxhc.system.service.app.IExaminationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.util.*;

@Service
public class ExaminationAppServiceImpl implements IExaminationService {

    @Autowired
    private ExaminationAppMapper examinationAppMapper;

    @Autowired
    private ExaminationUserQuestionMapper examinationUserQuestionMapper;

    @Autowired
    private QuestionBankMapper questionBankMapper;

    @Autowired
    private ExaminationQuestionMapper examinationQuestionMapper;

    @Override
    public List<Examination> getAllExamination(Examination examinationApp) {
        return examinationAppMapper.selectExaminationList(examinationApp);
    }


    /**
     * 新增考试的列
     *
     * @param examination 考试的列
     * @return 结果
     */
    @Override
    public int insertExamination(Examination examination)
    {
        Date startTime = DateUtil.parse(examination.getStartAt(), "yyyy-MM-dd");
        Date endTime = DateUtil.parse(examination.getEndAt(), "yyyy-MM-dd");
        int compareStart = DateUtil.compare(startTime,new Date());
        int compareEnd = DateUtil.compare(endTime,new Date());
        // 今天
        if(compareStart == 0){
            // 进行中
            examination.setStatus(1);
        }
        //
        if(compareStart == -1){
            if(compareEnd > -1){
                // 进行中
                examination.setStatus(1);
            }else{
                examination.setStatus(-1);
            }
        }
        // 待开始
        if(compareStart == 1){
            examination.setStatus(0);
        }
        examination.setCreateUserId(SecurityUtils.getUserId());
        int row =  examinationAppMapper.insertExaminationApp(examination);
        if(row == 1){
            int score = 0;
            List<QuestionBank> questionBankList = generateExam(20);
            // 插入考试题目
            for (QuestionBank questionBank : questionBankList) {
                score += questionBank.getScore();
                examinationQuestionMapper.insertExaminationQuestion(new ExaminationQuestion()
                        .setExaminationId(examination.getId())
                        .setQuestionId(questionBank.getId()));
            }
            examination.setScore(score);
            examinationAppMapper.updateExaminationApp(examination);
        }
        return row;
    }

    public List<QuestionBank> generateExam( int numberOfQuestions) {
        List <QuestionBank> questionBank =questionBankMapper.selectQuestionBankList(null);
        if (questionBank == null || questionBank.size() < numberOfQuestions) {
            throw new IllegalArgumentException("Question bank is too small to generate the exam.");
        }
        List<QuestionBank> shuffledQuestions = new ArrayList<>(questionBank);
        Collections.shuffle(shuffledQuestions);
        return shuffledQuestions.subList(0, numberOfQuestions);
    }


    /**
     * 修改考试的列
     *
     * @param examination 考试的列
     * @return 结果
     */
    @Override
    public int updateExamination(Examination examination)
    {
        return examinationAppMapper.updateExaminationApp(examination);
    }

    /**
     * 批量删除考试的列
     *
     * @param ids 需要删除的考试的列主键
     * @return 结果
     */
    @Override
    public int deleteExaminationByIds(Long[] ids)
    {
        return examinationAppMapper.deleteExaminationAppByIds(ids);
    }



    /**
     * 查询考试的列
     *
     * @param id 考试的列主键
     * @return 考试的列
     */
    @Override
    public Examination selectExaminationById(Long id)
    {
        return examinationAppMapper.selectExaminationAppById(id);
    }



    @Override
    public int submit(List<ExaminationUserQuestion> questionsAnswer) {
        return examinationUserQuestionMapper.batchInsert(questionsAnswer);
    }

    @Override
    public void statusCheck() {

        Examination examinationApp = new Examination();
        examinationApp.setStatus(-1);
        List<Long> startExaminations = new ArrayList<>();
        List<Long> endExaminations = new ArrayList<>();
        List<Examination> examinations = examinationAppMapper.selectExaminationListForTask();
        for (Examination examination : examinations) {
            if (examination.getStatus() == 0){
                String startAt = examination.getStartAt();
                Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, startAt);
                if (date.after(DateUtils.getNowDate())){
                    startExaminations.add(examination.getId());
                }
            }
            if (examination.getStatus() == 1){
                String endAt = examination.getEndAt();
                Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, endAt);
                if (date.before(DateUtils.getNowDate())){
                    endExaminations.add(examination.getId());
                }
            }
        }
        if (startExaminations.size() != 0){
            examinationAppMapper.updateStatusByIds(startExaminations,1);

        }
        if (endExaminations.size() != 0){
            examinationAppMapper.updateStatusByIds(endExaminations,-1);
        }
    }

    @Override
    public float calculateScore(String userId,String examinationId) {
        float score = 0;
        //用考试ID查询出考题
//        Map<Long, ExaminationQuestion> longExaminationQuestionMap =
//                examinationAppMapper.selectExaminationQuestionMap(examinationId);
//
//        //获取用户该场次考题
//        List<ExaminationUserQuestion> examinationUserQuestions =
//                examinationUserQuestionMapper.selectByUserAndExamination(userId, examinationId);
//
//        for (ExaminationUserQuestion examinationUserQuestion : examinationUserQuestions) {
//            Long questionId = examinationUserQuestion.getQuestionId();
//            ExaminationQuestion question = longExaminationQuestionMap.get(questionId);
//            if (question.getAnswer() == examinationUserQuestion.getAnswer()){
//                score += question.getScore();
//            }
//        }
        return score;
    }

    @Override
    public List<Examination> queryExaminationByUserId(String userId) {
        return examinationAppMapper.selectByUserId(userId);
    }
}
